<?php


namespace App\Exception\Handler;

namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class FromValidateExceptionHandler extends ExceptionHandler
{

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof ValidationException) {
            // 格式化异常数据格式
            $data = json_encode([
                'code' => $throwable->getCode(),
                // 获取异常信息
                'message' => $throwable->validator->errors()->first(),
                'data' => [],
            ],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            return $response->withStatus(400)->withBody(new SwooleStream($data));
        }

        return $response;
    }

    // 异常处理器处理该异常
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}